<?php ob_start();?>
<?php 
	$root = $_SERVER['DOCUMENT_ROOT'];
	/*TODO: burasi duzeltilecek*/
 	include($root.'/standart/head.php');
 	include($root.'/standart/dateHeader.php');
 	include($root.'/standart/dbconnect.php');
 	include($root.'/cart/ShoppingCart.class.php');
 	include($root.'/cart/MenuItem.class.php');
?>
<?php
session_start();
if(isset($_COOKIE['tzRemember'])){
	$_SESSION['id'] = $_COOKIE["gevezeUser"];
	$_SESSION['usr'] = $_COOKIE["gevezeMail"];
	
	$items = array();
	$prices = array();
	$shoppingCart;
	$lastOrderId;
	$totalAmount;
	$list = array();
}
if(isset($_GET['logoff']))
{
	$_SESSION = array();
	session_destroy();
	setcookie("tzRemember","", time() -3600);
	setcookie("gevezeMail","", time() -3600);
	setcookie("gevezeUser","", time() -3600);
	header("Location: cart.php");
	exit;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Geveze Cafe | Sepetim</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">


<!-- Bootstrap --> 
<link href="css/bootstrap.css" rel="stylesheet" /> 
<!-- <link href="css/bootstrap.min.css" rel="stylesheet" />-->

<!--Boostrap-Responsice Css-->
<link href="css/bootstrap-responsive.css" rel="stylesheet" type="text/css">
<link href="css/style.css" rel="stylesheet" /> 

<!--Google Fonts-->
<link href='http://fonts.googleapis.com/css?family=Oswald|Lato|Roboto:400,500,700|Open+Sans:600,700,300' rel='stylesheet' type='text/css'>

<!--Custom Css-->
<link href="css/custom.css" rel="stylesheet" type="text/css">
<!--Colors Css-->
<link href="css/colors_3.css" rel="stylesheet" type="text/css">

<!--Scrollbar Css-->
<link href="css/jquery.mCustomScrollbar.css" rel="stylesheet" />
<!--Pie Chart Css-->
<link rel="stylesheet" type="text/css" href="css/style.css" media="screen">

<!-- <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.1/css/font-awesome.css" rel="stylesheet">  -->


<!--Date Time Picker CSS -->
<link href="css/bootstrap-datetimepicker.css" rel="stylesheet">

<!--Date Picker-->
<link href="css/datepicker3.css" rel="stylesheet">


<link rel="stylesheet" type="text/css" href="css/slide.css" media="screen" />
<link href="css/tinyBox.css" rel="stylesheet" type="text/css" media="screen"/>

</head>

<body onload="loadPage()">
<div id="toppanel">
	<div id="panel">
		<div class="content clearfix">
	        <?php
			if(!$_SESSION['id']):
			?>
			<div class="right">
				<!-- Login Form -->
				<form class="clearfix" action="" method="post" id="loginForm">
					
					<table style="border: none; width: 100%;">
						<tr>							
							<td>
								<input class="field" type="text" name="username" id="username" value="" size="23" placeholder="E-Mail"/>
							</td>
							<td>
								<input class="field" type="password" name="password" id="password" size="23" placeholder="Şifre" />
							</td>							
							<td>
								<a style="cursor: pointer;" onclick="forgetPass()">Şifremi Unuttum</a>
							</td>
						</tr>
						<tr>
							<td>
								<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> &nbsp;Beni hatırla</label>
							</td>
							<td>
								<input class="btn btn-success btn-xl" style="line-height: 12px; padding-left:30px; padding-right:30px;" type="button" name="submit" value="Giriş"  onclick="sendData()" />
							</td>
							<td>
								<input class="btn btn-info btn-lg"  value="Kayıt Ol" style="cursor: pointer; right: 0px; float: right; line-height: 12px;" type="button" onclick="window.location.replace('register.php')"/>
							</td>
						</tr>
					</table>
				</form>
			</div>
            <?php
			
			else:
			
			?>
            
            <div class="right">
            	<input class="btn btn-danger btn-xl" type="button" style="cursor: pointer; right: 0px; float: right; line-height: 12px; padding-right:30px; padding-left:30px;" onclick="window.location.replace('?logoff')" value="Çıkış"/>
            	<div class="loginTop"><?php echo $_SESSION['usr'] ? 'Merhaba '.$_SESSION['usr'] : '';?> <br/></div>
	            <div class="loginMenu">
	            	<div class="loginMenuLeft" onclick="window.location.replace('order-list.php')"> Siparişlerim </div>
	            	<div class="loginMenuMid" onclick="window.location.replace('user-info-change.php')"> Kişisel Bilgilerim </div>
	            	<div class="loginMenuMid" onclick="window.location.replace('add-address.php')"> Adres Ekle</div>
	            	<div class="loginMenuRight" onclick="window.location.replace('change-password.php')"> Şifre Değiştir </div>
	            </div>
            </div>
            <?php
			endif;
			?>
		</div>
	</div> <!-- /login -->	
    <!-- The tab on top -->	
	<div class="tab">
		<ul class="login">
	    	<li class="left">&nbsp;</li>
	        <li id="toggle">
				<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Kullanıcı Bilgileri':'Üye Girişi | Yeni Üye';?></a>
				<a id="close" style="display: none;" class="closex" href="#">Bilgi Alanını Kapat</a>			
			</li>
	    	<li class="right">&nbsp;</li>
		</ul> 
	</div> <!-- / top -->
</div> <!--panel -->
<!--Wrapper Start-->
<div id="wrapper"> 
  <!--Header Start-->
<header id="header"> <!--<span class="icon-dish"></span>-->
    <div class="container">
      <div class="row-fluid">
        <div class="span3">
          <div class="logo"><a href="index.php"><img src="images/logo-gevezecafe.png" alt="img"></a></div>
        </div>
        <div class="span8 margin-non">
          <div class="top-container">
            <div class="span5"></div>
            <div class="span7">
             </div>
          </div>
          <div class="navbar navbar-inverse nav-bar">
            <div class="navbar-inner nav-bar-inner">
              <button type="button" class="btn-lg btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
              <div class="nav-collapse collapse top-nav">
                <ul class="nav">
                  <li class="dropdown"> <a class="dropdown-toggle" href="index.php">ANA SAYFA</a>
                  </li>
                  <li class="dropdown"> <a class="dropdown-toggle" href="menu.php" >MENÜ</a>
                  </li>
                  <li class="dropdown"> <a class="dropdown-toggle" href="cart.php" >SEPETİM</a>
                  	<?php 
                  		$shoppingCart = new Shopping_Cart('sepet');
                  		$quantity = $shoppingCart->getAllQuantity();
					?>
                  	<div class="cartCount" id="cartCount" <?php if($quantity == 0){ ?> style="display: none;" <?php } ?>><?php echo $quantity;?></div>
                  </li>
				  <li class="dropdown"> <a class="dropdown-toggle" href="about.php" >HAKKIMIZDA</a>
                  </li>
                  <li class="dropdown"> <a class="dropdown-toggle" href="contact.php" >İLETİŞİM</a></li>
                </ul>
              </div>
              <!--/.nav-collapse --> 
            </div>
            <!-- /.navbar-inner --> 
          </div>
          <!--Nav End--> 
        </div>
      </div>
    </div>
  </header>
  <!--Header End--> 
  
  <!--Banner Start-->
  <section id="banner" class="height">
    <div class="contact-banner"><img src="images/inner-banner-4.jpg" alt="img"></div>
  </section>
  <!--Banner End--> 
  
   <!--Content Area Start-->
  <section id="content" class="container"> 
    <!--Blog Page Section Start-->
    <section class="blog-page-section">
      <div class="row-fluid">
        <div class="span12">
          <div class="heading">
            <h1>Sepetim</h1>
          </div>
        </div>
        <!--Blog Post End--> 
        
      </div>
    </section>
    <!--Blog Page Section End--> 
    <div>
    <!--Cart Start-->
    </div>
    <section class="cart-page">
      <div class="row-fluid">
        <div class="page_content">
          <div class="span12" id="block_content_first">
            <article class="span12 mbtm  first">
              <div class="woocommerce">
                <div class="cart_table_holder">
                  <form id="cartSubmit" method="post" >
                    <div class="clear"></div>
                    <table width="100%" cellpadding="10" border="0" id ="cartTable">
                      <thead>
                        <tr> 
                          <!--<th class="product-thumbnail">&nbsp;</th>-->
                          <th width="60%" colspan="2" class="product-name">Ürün</th>
                          <th width="10%" class="product-price">Fiyat</th>
                          <th width="15%" class="product-quantity">Adet</th>
                          <th width="10%" class="product-subtotal">Toplam</th>
                          <th width="5%" class="product-remove"> </th>
                        </tr>
                      </thead>
                      <tbody id= "cartInfo">
                      <?php 
                        //session_start ();
                        $db = connect(); 
                        $shoppingCart = new Shopping_Cart('sepet');
						$cartMenuIdList = $shoppingCart->getInList();
						$totalAmount = 0;
						if(!empty($cartMenuIdList)){
						    $cartMenuQuery ="SELECT * FROM MENU WHERE ID IN ($cartMenuIdList)";
	                        $cartMenuList = $db->query($cartMenuQuery) or die($cartMenuQuery."<br/><br/>".mysql_error());
	                        while($cartMenu = $cartMenuList->fetch_assoc()){
								$priceQuery="SELECT * FROM PRICE_LIST WHERE MENU_ID = {$cartMenu['ID']} AND APPLICABLE_FROM<now() ORDER BY APPLICABLE_FROM DESC LIMIT 1";
								$priceResult = $db->query($priceQuery) or die($priceQuery."<br/><br/>".mysql_error());
								while($priceRecord = $priceResult->fetch_assoc()){
									$price = $priceRecord['PRICE'];
									$prices[] = $priceRecord;
								}
								$quantity = $shoppingCart->getQuantityByMenuId($cartMenu['ID']);
		                        ?>
		                        <tr class="cart_table_item" menuID = '<?php echo $cartMenu['ID']; ?>'>
		                          <!-- Remove from cart link --> 
		                          
		                          <!-- The thumbnail -->
		                          <td width="20%" class="img"><a href="#"><img width="90" height="90" alt="drum" class="attachment-shop_thumbnail wp-post-image" src="<?php echo ($cartMenu['PICTURE']==null?"images/cart-one.jpg":$cartMenu['PICTURE']); ?>"></a></td>
		                          
		                          <!-- Product Name -->
		                          <td width="40%;" class="product-name" id="product-name"><a href="#"><?php echo $cartMenu['PRODUCT_NAME']; ?></a></td>
		                          
		                          <!-- Product price -->
		                          <td class="product-price price" id='product-price'><span class="amount"><?php echo $price;?> TL</span></td>
		                          
		                          <!-- Quantity inputs -->
								  <td class="product-quantity" id="pq">
									<div class="quantity buttons_added">
										<input type="button" class="minus" value="-" onclick="changeQuantity('-', '<?php echo $cartMenu['ID']; ?>', <?php echo $price; ?>)">
										<input type="text" class="input-text qty text" onkeypress="validate(event)" onchange="changeQuantity('', '<?php echo $cartMenu['ID']; ?>', <?php echo $price; ?>)" id="inpMenuQuantity<?php echo $cartMenu['ID'];?>" maxlength="2" title="Qty" size="4" value="<?php echo $shoppingCart->getQuantityByMenuId($cartMenu['ID']); ?>" max="" min="" step="1" name="">
										<input type="button" class="plus" value="+" onclick="changeQuantity('+', '<?php echo $cartMenu['ID']; ?>', <?php echo $price; ?>)">
									</div>
								  </td>
		                          <!-- Product subtotal -->
		                          <td class="product-subtotal price" id="product-amount"><span class="amount" id="totalMenuPrice<?php echo $cartMenu['ID'];?>"><?php echo number_format($price*$quantity, 2);?> TL</span></td>
		                          <td class="product-remove"><a title="Remove this item" class="cbtn" style="cursor: pointer;" onclick="removeCartItem('<?php echo $cartMenu['ID']; ?>')" >Kaldır</a></td>
		                        </tr>
		                        
		                        <?php 
		                        $lastOrderQuery = "SELECT MAX(Order_Id) FROM ORDER_ITEMS"; 
		                        $lastOrderQueryResult = $db->query($lastOrderQuery);
		                        while($queryRecord = $lastOrderQueryResult->fetch_assoc()){
		                        	$lastOrderId = $queryRecord['MAX(Order_Id)'];
		                        }
		                        $totalAmount = $totalAmount + $price*$quantity;
		                        $items[] = $cartMenu;
							}		
// 							orderFunction();
						}
                        ?>
                        <?php
                        /*
							function orderFunction(){
							    $db = connect();
		                        echo 'Count of Order Items...', count($GLOBALS['items']);
		                        echo '</br>';
		                        echo 'Count of Prices ...', count($GLOBALS['prices']);
		                        echo '</br>';
		                        echo $GLOBALS['prices']['PRICE'];
		                        for ($x = 0; $x < count($GLOBALS['items']); $x++) {
									echo '</br>';
		                        	$mId = $GLOBALS['items'][$x]['ID'];
		                        	$q = $GLOBALS['shoppingCart']->getQuantityByMenuId($GLOBALS['items'][$x]['ID']);
		                        	$p = $GLOBALS['prices'][$x]['PRICE'];
                        			echo 'menu ID: ',$mId;
                        			echo ' ';
                        			echo 'quantity: ',$q;
                        			echo ' ';
                        			echo 'price: ',$p;
								} 
		                        echo '</br>New Order ID: ',$GLOBALS['lastOrderId'] + 1;
		                        echo '</br>Total Amount: ',$GLOBALS['totalAmount'];
		                        $sA = $_GET['cmbAdr'];
		                        echo '</br>',$sA;
							}
							function insertOrders(){
								$shipAddr;
							}
							*/
						?>
						<div id="info" name="info" items="<?php echo $items?>" prices="<?php echo $prices ?>" totalAmount="<?php echo $totalAmount ?>">
						</div>
                      </tbody>
					  <tfoot>
					  <tr>
					  	<td width="15%" class="total_price" colspan="8>
					  		<div class="cart_totals ">
                              <table cellspacing="0" class="total_cart">
                                <tbody>
                                  <tr>
                                    <td colspan="2"><h2>Sipariş Notu:</h2></td>
                                    <td colspan="4"></td>
                                    <td colspan="3"><textarea placeholder="En fazla 200 karaktere kadar sipariş notunuzu girebilirsiniz" id ="orderNotes" maxlength="200" rows="2" wrap="soft"></textarea></td>
                                  </tr>
                                </tbody>
                              </table>
                            </div>
					  	</td>					  	
					  </tr>
                        <tr>
                          <td width="15%" class="total_price" colspan="8">
                          	<div class="cart_totals ">
                              <table cellspacing="0" class="total_cart">
                                <tbody>
                                  <tr>
                                    <td colspan="2"><h2>Toplam Ücret:</h2></td>
                                    <td colspan="2"><h2 style="text-align: right; padding-right: 105px;" id="totalPrice"><?php echo number_format($totalAmount, 2); ?> TL</h2></td>
                                  </tr>
                                </tbody>
                              </table>
                            </div>
                          </td>
                        </tr>
                      </tfoot>
                    </table>
                    <div class="cart_btn_wrapper">
                      <input type="submit" value="Sepeti Güncelle" name="update_cart" class="pull-left continue_shopping button cbtn">
                      <input type="button" value="Sepeti Boşalt" name="empty_cart" class="pull-left continue_shopping button cbtn" onclick="emptyCart()">
						<?php 
						if(isset($_SESSION['id'])) {
							$userId = $_SESSION['id'];
							$userAddressQuery = "SELECT * FROM ADDRESS WHERE ID IN (SELECT ADDRESS_ID FROM USERS_ADDRESS WHERE USER_ID = $userId)";
	                        $userAddressList = $db->query($userAddressQuery) or die($userAddressQuery."<br/><br/>".mysql_error());
						?>
							<select name="cmbAdr" class="pull-right form-control" id="slcAddress" style="height: 40px;" onchange="checkBoxes()">
							<option value="0">Seçiniz</option>
							<?php
							while($address = $userAddressList->fetch_assoc()){ ?>
								<option value="<?php echo $address['ID']; ?>"><?php echo $address['ADDRESS_DEFINITION']; ?></option>
							<?php 
							} 
							?>
							</select>
							
							<input type="button" id="sbmBtn" value="Sipariş Ver →" name="proceed" class="pull-right checkout_btn checkout-button button alt" onclick="orderMenu()" style="margin-left: 5px;margin-right: 5px;" >
							<input type="text"  name="orderTime" id="orderTime" class="pull-right form-control dtPicker" style="height: 40px;" onchange="checkBoxes()"/>
							<input type="text"  name="orderDate" id="orderDate" class="pull-right form-control" style="height: 40px; padding-left: 5px;" onchange="checkBoxes()"/>
							<input type="hidden" id="cDate" >
						<?php
						}
						else {
						?>
							<input type="button" id="sbmBtn" value="Sipariş Ver →" name="proceed" class="pull-right checkout_btn checkout-button button alt">
						<?php
						}
						?>
                      <input type="hidden" value="9b478202bd" name="_n" id="_n">
                      <input type="hidden" value="" name="_wp_http_referer">
                    </div>
                  </form>
                </div>
              </div>
            </article>
          </div>
        </div>
      </div>
    </section>
    <!--Cart End--> 
    
  </section>
  <!--Content Area End--> 
    
  <!--Footer Area Start-->
  <footer id="footer">
    <div class="row-fluid">
      <section class="footer-section-1">
        <div class="bg-opacity-2">
          <div class="container">
            <div class="span3">
              <div class="featured-dishes">
                <h4>Sizin İçin Seçtiklerimiz</h4>
				<ul>
				<?php
				/*
				$rows = 0;
				$featuredMenuList->data_seek(0);
				while($featuredMenu = $featuredMenuList->fetch_assoc()){
					if(is_null($featuredMenu['PICTURE'])){
						$menuImg = "images/featured-footer-img-1.jpg";
					}
					else{
						$menuImg = $featuredMenu['PICTURE'];
					}
				?>
					<li>
						<div class="frame"><img src="<?php echo $menuImg; ?>" style="width: 113px; height: 50px;" alt="img"></div>
						<div class="text"> <strong class="title"><?php echo $featuredMenu['PRODUCT_NAME'];?></strong> </div>
					</li>
				<?php
					$rows++;
					if($rows==3){
						break;
					}
				}
				*/
				?>
				</ul>
              </div>
            </div>
            <div class="span1">
            </div>
			<div class="span2">
              <div class="recent-post">
                <div class="featured-dishes">
                  <h4>Site Haritası</h4>
                  <ul>
                    <li class="site-map">
                      <div id="address" class="recent-post-text"> <strong class="title"><a href="index.php">Ana Sayfa</a></strong></div>
                    </li>
                    <li class="site-map">
                      <div id="address" class="recent-post-text"> <strong class="title"><a href="menu.php">Menü</a></strong></div>
                    </li>
                    <li class="site-map">
                      <div id="address" class="recent-post-text"> <strong class="title"><a href="menu.php">Siparişler</a></strong></div>
                    </li>
                    <li class="site-map">
                      <div id="address" class="recent-post-text"> <strong class="title"><a href="about.php">Hakkımızda</a></strong></div>
                    </li>
                    <li class="site-map">
                      <div id="address" class="recent-post-text"> <strong class="title"><a href="contact.html">İletişim</a></strong></div>
                    </li>
                  </ul>
                </div>
              </div>
            </div> 			
            <div class="span3">
              <div class="recent-post">
                <div class="featured-dishes">
                  <h4>Adres</h4>
                  <ul>
                    <li>
                      <div id="address" class="recent-post-text"> <strong class="title">IYTE Teknopark, Gülbahçe<br/>Urla İzmir</strong> </div>
                    </li>
                    <li>
                      <div id="phone" class="recent-post-text"> <strong class="title">Telefon: 0232 765 90 95<br/></strong> </div>
                    </li>
                    <li>
                      <div id="email" class="recent-post-text"> <strong class="title">Email: info@gevezecafe.com</strong> </div>
                    </li>
                  </ul>
                </div>
              </div>
            </div>           
            <div class="span3">
              <div class="watch-box">
                <div class="watch-img"> <img src="images/watch-img.png" alt="img">
                  <div class="time-box"> <strong class="time">Hafta İçi Her Gün</strong> <strong class="time">08:00 - 19:00</strong> </div>
                </div>
                <strong class="book-table">Siparişleriniz İçin: <span class="red">0232 765 9095</span></strong> 
              </div>
            </div>
          </div>
        </div>
      </section>
      <!--Footer Section Section 3 Start-->
      <section class="footer-section-3">
        <div class="container">
          <div class="span6">
            <div class="copy-section"><strong class="copy">&copy; 2014 Teknopark Geveze Cafe, Designed by <a href="http://gevezecafe.com/" class="link" target="_blank">gevezecafe.com</a></strong></div>
          </div>
          <div class="span6">
            <div class="footer-social-box">
              <ul>
                <li class="social-icon-1"><a href="#">p</a></li>
                <li class="social-icon-2"><a href="#">twitter</a></li>
                <li class="social-icon-3"><a href="#">facebook</a></li>
                <li class="social-icon-4"><a href="#">facebook</a></li>
                <li class="social-icon-5"><a href="#">facebook</a></li>
                <li class="social-icon-6"><a href="#">facebook</a></li>
              </ul>
            </div>
          </div>
        </div>
      </section>
      <!--Footer Section Section 3 End--> 
    </div>
  </footer>
  <!--Footer Area End--> 
  <p id="back-top"> <a href="#top" class="back-top">Back to Top</a> </p>
</div>
<div class="cartCount" style="width: 0px; height: 0px; position: absolute; opacity: 0.7; z-index:850; filter: alpha(opacity=70);" id="addCart">+1</div>

<!-- Modal Begins -->
			<div id="insertResult" class="modal hide fade">
			  <div class="modal-body" id="modalBody">
			  </div>
			  <div class="modal-footer" style="text-align: center;">
			    <button type="button" data-dismiss="modal" class="btn" data-value="0" onclick="emptyCart();">Tamam</button>
			  </div>
			</div>
<!-- Modal Ends -->
			
<!-- jQuery --> 
<script type="text/javascript" src="js/jquery-1.8.1.min.js"></script><!-- lib Js --> 
<script src="js/bootstrap.js" type="text/javascript"></script><!-- Boostrap Js --> 

<!-- Html5 Js -->
<script src="js/html5.js" type="text/javascript"></script>
<!--Ajax Operations Js--> 
<script type="text/javascript" src="../js/ajax.js"></script>

<!--Moment JS -->
<script src="js/moment.js"></script>
<script src="js/moment-with-locales.js"></script>

<!--Date Time Picker JS -->
<script src="js/bootstrap-datetimepicker.min.js"></script><!--Date Picker Js--> 

<!--Date Picker Js--> 
<script src="js/bootstrap-datepicker.js"></script><!--Date Picker Js--> 
<script src="locales/bootstrap-datepicker.tr.js"></script><!--Date Picker Js--> 

<!-- Custom Scripts --> 
<script src="js/custom.js" type="text/javascript"></script><!-- Custom Scripts --> 

<!-- Calender --> 
<script type='text/javascript' src='js/jquery-ui-1.8.23.custom.min.js'></script><!-- Calender Js--> 
<script type="text/javascript" src="js/login.js"></script>

<script type="text/javascript">

function removeCartItem(menuId){
	var url = 'cart/cartController.php?ACTION=REMOVE&MENU_ID=' + menuId;
	ajx(url, '');
	location.reload(true);
}


function emptyCart(){
	var url = 'cart/cartController.php?ACTION=EMPTYCART';
	ajx(url, '');
	location.reload(true);
}

function validate(evt) {
	var theEvent = evt || window.event;
  	var key = theEvent.keyCode || theEvent.which;
  	key = String.fromCharCode( key );
  	var regex = /[1-9]/;
  	if( !regex.test(key) ) {
    	theEvent.returnValue = false;
    	if(theEvent.preventDefault) theEvent.preventDefault();
  	}
}

function changeQuantity(operation, menuId, price){

		var quantity = parseInt(document.getElementById("inpMenuQuantity"+menuId).value);


		var firstTotalPrice = parseFloat(document.getElementById("totalMenuPrice"+menuId).innerText.replace(" TL", ""));

		if(operation=="+" && quantity<99 ){
			document.getElementById("inpMenuQuantity"+menuId).value = quantity +1;
		}
		else if(operation=="-" && quantity>1){
			document.getElementById("inpMenuQuantity"+menuId).value = quantity -1;
		}

		quantity = parseInt(document.getElementById("inpMenuQuantity"+menuId).value);
		
		var url = 'cart/cartController.php?ACTION=CHANGEQUANTITY' + '&QUANTITY=' + parseInt(document.getElementById("inpMenuQuantity"+menuId).value) + '&MENU_ID=' + menuId;
		var sumQuantitiy = ajx(url, '').trim();
		$('#cartCount').html(sumQuantitiy);
		if(sumQuantitiy > 0){
			$('#cartCount').css('display', 'block');
		}else{
			$('#cartCount').css('display', 'none');
		}

		var totalMenuPrice = parseFloat(price) * parseFloat(quantity);
		
		document.getElementById("totalMenuPrice"+menuId).innerText = totalMenuPrice.toFixed(2) + " TL";
		
		var totalCartPrice = parseFloat(document.getElementById("totalPrice").innerText);

		totalCartPrice = totalCartPrice - firstTotalPrice + totalMenuPrice;

		document.getElementById("totalPrice").innerText = totalCartPrice.toFixed(2) + " TL";
	}
	//Getting Json Table Data as Json
	function getJson(){
		var productNames = [];
		var productPrices = [];
		var productQuantities = [];
		var productTotals = [];
		var productIds = [];

	    var table = document.getElementById('cartInfo');
	    var tr = table.getElementsByTagName('tr');
	    var jObject = {};
// 		var order = [];
// 	    jObject.orders = order;
	    for (var i = 0; i < tr.length; i++){
	        var names = tr[i].getElementsByClassName('product-name');
	        var prices = tr[i].getElementsByClassName('product-price');
	        var quantities = tr[i].getElementsByClassName('product-quantity');
	        var total = tr[i].getElementsByClassName('product-subtotal');	        
	        var mId = tr[i].getAttribute('menuid');
	        productIds.push(mId);
	        productNames.push(names);
	        productPrices.push(prices);	 
	        productQuantities.push(quantities);	 
	        productTotals.push(total);
	    }
	    for (var i = 0; i<productNames.length;i++){
		    	var n0 = productIds[i];
				var n1 = productNames[i][0].innerText;
				var n2 = productPrices[i][0].innerText;
				var n3 = productQuantities[i][0].children[0].children[1].value;
				var n4 = productTotals[i][0].innerText;
				var order = {
				"menuId":n0,
				"name":n1,
				"price":n2,
				"quantity":n3,
				"total":n4
						}
				jObject[i] = order;
		    }
	    /*
        console.log(productNames);
        console.log(productPrices);
        console.log(productQuantities);
        console.log(productTotals);
        */
	    return jObject;
	}

	function orderMenu(){
// 		var formData = $('#cartSubmit').serialize();
		var totalAmount = parseFloat(document.getElementById('totalPrice').innerText);
		var addressId = document.getElementById('slcAddress').value;
// 		var orderDate = document.getElementById('orderDate').value;
		var orderDate = $('#cDate').attr('date');
		var orderNotes = $('#orderNotes').val();
		
// 		console.log(orderDate);
		
		var jObject = { 
				"addressId":addressId, 
				"orderDate":orderDate, 
				"totalAmount":totalAmount,
				"orderNotes":orderNotes
				};
		var formData =  JSON.stringify(jObject);
		if(totalAmount>0){
// 			addressId = '1';
			if(addressId!='0'){
				//insert at...
				//TODO Ajax call
				//Global variable'ları aktar ajax sayfasına
				
// 				console.log(JSON.stringify(getJson()));
				var jsonData = JSON.stringify(getJson());
				$.ajax( {
	    			type: "POST",
	    			url: 'cart-sent.php',
	    			data:  {'jsonData':jsonData, 'formData':formData},// 					
	    			contentType: "application/x-www-form-urlencoded; charset=UTF-8",
	    			success: function(data, textStatus, jqXHR)
	    			{
	    				$("#modalBody").empty();    
	    		        $("#modalBody").append("Siparişiniz");
	    		    	$("#modalBody").append("<br/>");
	    		    	$("#modalBody").append("<br/>");
	    		    	$("#modalBody").append("Sipariş No:");
	    		    	$("#modalBody").append("<b>"+" "+data+"</b>");
	    		    	$("#modalBody").append("<br/>");
	    		    	$("#modalBody").append("ile kaydedilmiştir!");
	    		    	$("#insertResult")
	    		    	.modal({ backdrop: 'static', keyboard: false });
//	     					$( "#resultDiv" ).html( data );
						console.log("Ajax Success");
						
// 	    					openNewUnit(data, 'success');
	    			},
	    			complete: function() {
	                   //window.location.reload();
	                }
					
			});
				
				
			}
			else{
				alert('adres hatali');
			}
		}
		else{
			alert('tutar 0...');
		}
	}
	//Input text için tarih alanı olarka kullanılıyor. Default input date kullanıldı. 
	// DATE TIME PICKER KULLANILACAK
	function loadPage(){
		<?php $isSet = 0; 
		if(isset($_COOKIE['tzRemember'])){		
			$isSet = 1;
		}  ?> 
		var session = <?php echo $isSet ?>;
		if(session != 0){
			//console.log(session);
			
			var oDate = document.getElementById("orderDate").value == "";
			var totalAmount = parseFloat(document.getElementById('totalPrice').innerText);
			var addressId = document.getElementById('slcAddress').value;
	
			$("#sbmBtn").prop("disabled", true);
	
			var currentDate = new Date();
			  $("#orderDate").datepicker({
				  startDate: currentDate,
				    language: "tr",
				    autoclose: true,
				    //format: 'yyyy/m/d',
				    //daysOfWeekDisabled: "0,6",
					todayHighlight: true
			  }).datepicker("setDate",currentDate);		  
		}
		
        $(function () {
            $('#orderTime').datetimepicker({
                language: 'tr',
                useCurrent: true,
                pickDate: false
            });
            
        });
        var lines = 2;
        
        $('#orderNotes').keydown(function(e) {
            
            newLines = $(this).val().split("\n").length;
            
            if(e.keyCode == 13 && newLines >= lines) {
                return false;
            }
            else {
            }
        });
/*
		var date = Date(); //moment($("#olddate").text(), "MM/DD/YYYY");
		var day = date.now();
		console.log(day);
	    /*
	    day.add('days', 1)
	    var newDate=day.toDate();    
	    $("#datepicker").datepicker();
	   
		*/
		//document.getElementById('orderDate').value = Date();
		//var t = document.getElementById('orderDate').value = Date();
		//console.log(t);
	}
	function checkBoxes(){	
		var oDate = document.getElementById("orderDate").value == "";
		var oTime = document.getElementById("orderTime").value == "";
		var totalAmount = parseFloat(document.getElementById('totalPrice').innerText);
		var addressId = document.getElementById('slcAddress').value;
			if(oDate!=true && totalAmount!=0 && addressId!=0 && oTime != true){
				//Enable Btn, change class
				$("#sbmBtn").prop("disabled", false);
				$("#sbmBtn").attr("class", "pull-right continue_shopping button cbtn");
			}
			else{
				//Disable btn, change class
				$("#sbmBtn").prop("disabled", true);
				$("#sbmBtn").attr("class", "pull-right checkout_btn checkout-button button alt");				
			}

			var date = document.getElementById("orderDate").value;
			if(!oDate){
				var date = $('#orderDate').val();
			}
			if(!oTime){
				var time = $('#orderTime').val();
			}
			if(date != undefined && time != undefined){
				var currentDate = date+' '+time;
// 				console.log(currentDate);
				parsedDate = date.split('.');
				var d = parsedDate[0];
				var m = parsedDate[1];
				var y = parsedDate[2];
				
				var newDate = y + "-" + m + '-' + d +' '+time;
				$('#cDate').attr('date', newDate);
			}else{
				$('#cDate').attr('date', null);
				$('#cDate').attr('time', null);
			}
		
	}
</script>
		
<!--Wrapper End-->
</body>
</html>
<?php disconnect($db); ?>
<?php ob_flush(); ?>